home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1500 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  76 lines

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: What the hell is THIS?!
  5. Date: 14 Jan 1996 19:51:46 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4dbmsi$47c@news.iag.net>
  8. References: <4d6rgh$rfu@abel.cc.sunysb.edu> <4d7g6u$j0l@umbc9.umbc.edu>
  9. NNTP-Posting-Host: pm3-orl13.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <4d7g6u$j0l@umbc9.umbc.edu>, schlein@umbc.edu says...
  13. >
  14. >Bommasamudram Madhusudan <bmadhusu@engws12.ic.sunysb.edu> wrote:
  15. >|> hi guys;
  16. >|> 
  17. >|> I'm going nuts trying to figure this out;
  18. >|> 
  19. >|> Can someone explain what
  20. >|> 
  21. >|>   int (*p)[3]  is?????
  22. >|> 
  23. >|>   Is this an array of pointers to integers 
  24. >|> 
  25. >|>   OR
  26. >|> 
  27. >|>   a pointer to an array of integers?? HELP!
  28. >
  29. >According to cdecl:
  30. >
  31. >cdecl> explain int (*p)[3]
  32. >declare p as pointer to array 3 of int
  33. >
  34. >|> I can say things like:
  35. >|> 
  36. >|> (*p)[0] = 3; for e.g, but when I print the value using:
  37. >|> 
  38. >|>  printf("%d",(*p)[0]) I get a core dump!
  39. >
  40. >Exactly...Because it is a pointer, you need to associate some space
  41. >with it via malloc() or the like.
  42.  
  43. #include <stdio.h>
  44. #include <string.h>
  45. #include <stdlib.h> 
  46.  
  47. int main(void)
  48.    {
  49.    int (*p)[3], ary[4][3];
  50.    
  51.    p = ary;  /* p points to ary[0][0] */
  52.    p++;      /* p points to ary[1][0] */
  53.    
  54.    p[0][2] = 3; /* ary[1][2] now == 3 */
  55.    
  56.    p = malloc( 3 * sizeof(*p)); /* same as sizeof(int(*)[3]) */
  57.    if(p == NULL)
  58.       exit(EXIT_FAILURE);
  59.    
  60.    /* p now points to a dynamic 3x3 array of ints  */
  61.    p[1][2] = 2;
  62.    printf( "%d\n", p[1][2]); /* this will output 2 */
  63.    free(p);
  64.  
  65.    return (0);
  66.    }
  67.  
  68. The c.l.c faq list has some information on this.  It is available for
  69. anonymous ftp from rtfm.mit.edu /pub/usenet/comp.lang.c.
  70.  
  71.  
  72. -- 
  73. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  74. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  75.  
  76.